/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Chat.java
 *
 * Created on 01-mar-2012, 5:20:39
 */
package sistemadeproyectos;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.*;
import javax.swing.JOptionPane;

/**
 *
 * @author giancarlo
 */
public class Chat extends javax.swing.JFrame {

    /* Socket que mantiene la conexion del usuario con el servidor chat.*/
    private Socket conexion;
    
    /* Identificacion del Usuario*/
    private Usuario usuario;
    
    /* Equipo actual */
    private Equipo equipoActual;
    
    /** Entrada de datos asociado al socket**/
    private ObjectInputStream entrada;

    /** Salida de datos asociado al socket**/
    private ObjectOutputStream salida;

    /*Hilo encargado de escuchar los mensajes del servidor*/
    private Escucha_thr Escucha;
    
    
    /** Creates new form Chat */
    public Chat(Socket conexion, ObjectInputStream entrada,
            ObjectOutputStream salida, Usuario usuario, Equipo equipo) {
        initComponents();
        
        (this.conexion) = conexion;
        (this.entrada) = entrada;
        (this.salida) = salida;
        (this.usuario) = usuario;
        (this.equipoActual) = equipo;
        this.setTitle("Chat de " + this.usuario.getUsuario() + " en el equipo " + equipoActual.getIdEquipo());
        /* Las areas de texto no se pueden editar */
        (this.jTextArea1).setEditable(false);
        (this.jTextArea2).setEditable(false);
        this.getRootPane().setDefaultButton(jButton1);
        this.jTextField1.requestFocus();
        
        /* Vacio el area de escritura de texto */
        jTextField1.setText("");
        
        this.getRootPane().setDefaultButton(jButton1);
        
        /* Iniciamos el hilo que escuchha */
        (this.Escucha) = new Escucha_thr(entrada, jTextArea1, jTextArea2, this);
        (this.Escucha).start();        
    }
    
    /**
     * Cierra el socket; asi como la salida y entrada de datos del mismo.
     */
    private void limpiar_socket() {
        try { 
          (this.entrada).close();
          (this.salida).close();
          (this.conexion).close();
        } catch (Exception e) {}
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane2.setViewportView(jTextArea1);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(Chat.class);
        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jTextArea2.setName("jTextArea2"); // NOI18N
        jScrollPane1.setViewportView(jTextArea2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                            .addComponent(jLabel2))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String Mensaje = jTextField1.getText();
        jTextField1.setText("");
        if (!(Mensaje.equals(""))) {
            Mensaje = (this.usuario.getUsuario()) + " dice: "+Mensaje;
            try { (this.salida).writeObject(Mensaje); }
            catch (Exception e) { 
                   JOptionPane.showMessageDialog(this, "Hubo un problema al mandar el mensaje: "+ e.getMessage(), 
                        "Error en Conexion", JOptionPane.ERROR_MESSAGE);
                   limpiar_socket();
                   this.dispose();
            }
        }
        jTextField1.requestFocus();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            (this.salida).writeObject("desconectar");
        }
        catch (Exception e) {
            limpiar_socket();
            this.dispose();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * Funcion de manejo de exepciones si ocurrio un problema con el hilo
     * que escucha mensajes del servidor.
     */
    public void terminacion(int i) {
        if (i == 1) {
            JOptionPane.showMessageDialog(this, "Hubo un fallo en la comunicacion. ", 
                "Error en Conexion", JOptionPane.ERROR_MESSAGE);
            jButton1.setEnabled(false);
        }
        else{
            System.out.println("normal");
            this.dispose();
        }
        limpiar_socket();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
               // new Chat().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}

class Escucha_thr extends Thread {
    private ObjectInputStream entrada;
    
    private javax.swing.JTextArea AreaTexto;
    
    private javax.swing.JTextArea AreaUsuarios;
    
    private Chat padre;
        
    public Escucha_thr(ObjectInputStream entrada, javax.swing.JTextArea Texto,
            javax.swing.JTextArea Usuarios, Chat padre) {
        this.entrada = entrada;
        this.AreaTexto = Texto;
        this.AreaUsuarios = Usuarios;
        this.padre = padre;
    }
    
    
    public void run() {
        boolean ejecutar = true;
        boolean normal = false;
        try {
            while (ejecutar) {
                ArrayList<String> Usuarios = new ArrayList<String> ();
                String str = (String)entrada.readObject (); /**Se lee lo que escribe el servidor y se escribe en la ventana de chat*/
                if (str.equals("desconectado")) {
                    ejecutar = false;
                    normal = true;
                }
                else if (str.equals("desconectado2")) {
                    (this.padre).terminacion(1);
                    ejecutar = false;
                }
                else { 
                    AreaTexto.append (str + "\n\n");
                    Usuarios = (ArrayList<String>)entrada.readObject();
                }
                
                /*Actualizamos la lista de Usuarios Conectados*/
                Iterator<String> iter = Usuarios.iterator(); 
                if (iter.hasNext()) {
                    AreaUsuarios.setText("");  
                    while(iter.hasNext()) { 
                        AreaUsuarios.append(iter.next()+"\n");	
                    }
                }
                
                /*terminamos la ejecucion del padre y del hilo*/
                if (normal == true) {
                   (this.padre).terminacion(0); //terminacion normal     
                }
                
            }
        } catch (Exception e) { 
            (this.padre).terminacion(1); //terminacion anormal
            //Cerramos la aplicacion
        }
        
    }
}